---
import { getCollection, getEntry, render } from "astro:content";
import InPageNavLayout from "../../layouts/InPageNavLayout.astro";

export async function getStaticPaths() {
    const entries = await getCollection("lionFundamentals");

    return [
        ...entries.map(entry => ({ params: { path: entry.id }})),
        {params: { path: undefined }}
    ]
}

const { path } = Astro.params;
const entry = await getEntry("lionFundamentals", path);

if (!entry) {
    // Handle Error, for example:
    throw new Error(`Could not find component by URL ${path}`);
}
const { remarkPluginFrontmatter } = await render(entry);

const loadDemoAttributes = {};
if (remarkPluginFrontmatter.mdjsStoriesPath) {
  loadDemoAttributes['data-import-path'] = remarkPluginFrontmatter.mdjsStoriesPath;
}

---

<InPageNavLayout entry={entry}>
  <load-demo {...loadDemoAttributes}></load-demo>

  <script>
    class LoadDemo extends HTMLElement {
      connectedCallback() {
        // a weird hack for Astro
        // in order to have script type=module, we cant specify any attributes to it
        // this MDJS breaks, because we need msjs-setup attribute
        // if we specify this attribute, then it's suddenly loses "type=module" and lazy import cannot be used inside

        // on top of that, to pass the variable from template (importPath) we can only do this through HTML element
        if (this.dataset.importPath) {
          import(`./_demos/${this.dataset.importPath}.js`);

          const currentScript = [...document.scripts].find(script => script.src === import.meta.url);
          currentScript.setAttribute('mdjs-setup', 'true');
          // another rocket - astro compatibility magic
          // we mast pass ".js" because it is stripped by rocket
          // so we get story file variable in simulator without it (as we want)
          currentScript.setAttribute('src', `/fundamentals/${this.dataset.importPath}`);
        }
      }
    }

    customElements.define('load-demo', LoadDemo);
  </script>
</InPageNavLayout>
